import os,glob
import yaml
import importlib
from loguru import logger
from constants import Report


def get_base_dir_realpath():
    current_dir = os.path.dirname(os.path.realpath(__file__))
    base_dir = "{}/..".format(current_dir)
    print(base_dir)
    return os.path.realpath(base_dir)


def get_obj(pack_str):
    """
    接受测试用例中的字符串包名，返回类的对象
    :param pack_str: 包名
    :return:object :返回类的对象
    """
    if '.' not in pack_str:
        raise RuntimeError('包名编写不正确，请以包名.类名显示')

    package_name = "."+pack_str[0:pack_str.rfind('.')]  # 获取包名及模块名
    class_name = pack_str[pack_str.rfind('.')+1:]     # 获取类名
    mod = importlib.import_module(package_name,package='pages')
    my_class = getattr(mod,class_name)
    my_obj = my_class()

    return my_obj


# 获取项目下某个目录的文件路径
def get_path(project_dir,file_name=None):
    path = os.path.join(os.path.dirname(
        os.path.dirname(
            os.path.abspath(__file__)
        )
    ),project_dir)
    if file_name is not None:
        path = os.path.join(path,file_name)
    return path


# 作用 ：将每一个yaml文件的数据转化为Python对象
def read_yaml_file(file_path,case_path):
    ret = []
    path = get_path(case_path,file_path)
    with open(path,'r',encoding='utf-8') as yamlFile:
        all_data = yaml.load_all(yamlFile, Loader=yaml.SafeLoader)
        for data in all_data:
            data['cases'].update(**{'file_name': get_yml_file_name(path, case_path)})
            logger.info("data:{}".format(data))
            temp_lst = [value for value in data.values()]        # 去掉大
            ret.extend(temp_lst)
        return ret


def get_yml_file_name(yml_file,case_path):
    """
    data后面的路径
    :param yml_file: 代表yml文件的全路径
    :return:
    """
    file_path = case_path + yml_file.split(case_path)[1]
    return file_path


# 删除测试报告
def delete_file(file_path,ends='*.html'):
    path = file_path + '/' + ends
    for file in glob.glob(path):
        os.remove(file)


# 修改测试报告文件名
def modify_report_name(filename=Report.REPORT_FILE):
    html_path = get_path('reports','*'+Report.REPORT_FILE)
    html_file = glob.glob(html_path)[0]     # 返回第一个文件
    # 修改后的文件名为：
    modify_name  = os.path.join(os.path.dirname(html_file),filename)
    os.rename(html_file,modify_name)
    logger.info("修改后的测试报告文件名:{}".format(modify_name))


if __name__ == '__main__':
    # print(read_yaml_file('login/login.yml'))
    # E:\python_project\api_test_xzs\api_data\home_page.yml
    # modify_report_name()
    delete_file(get_path('reports'))
